package site.tiangao.async.kt

import com.ning.http.client.AsyncHttpClient
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking

val httpClient = AsyncHttpClient()

//fun main(args: Array<String>) {
//    exec()
//    exec()
//}

fun test1(i: Long) {
    val start = System.currentTimeMillis()
    println("${Thread.currentThread().name} $start start $i")
    runBlocking {
        println("${Thread.currentThread().name} ${System.currentTimeMillis()} runBlocking start $i")
        delay(i)
        test2(start, i)
        println("${Thread.currentThread().name} ${System.currentTimeMillis() - start} runBlocking end $i")
    }
    println("${Thread.currentThread().name} ${System.currentTimeMillis() - start} end $i")
}

fun test2(start: Long, i: Long) {
    println("${Thread.currentThread().name} --- ${System.currentTimeMillis() - start} start $i")
    val istart = System.currentTimeMillis()
    runBlocking {
        println("${Thread.currentThread().name} --- ${System.currentTimeMillis() - start} runBlocking start $i")
        delay(20)
        println("${Thread.currentThread().name} --- ${System.currentTimeMillis() - istart} runBlocking end $i")
    }
    println("${Thread.currentThread().name} --- ${System.currentTimeMillis() - start} end $i")
}


private fun exec() {
    runBlocking {
        val start = System.currentTimeMillis()
        val redis = async { getResponse("redis", start) }
        val dal = async { getResponse("dal", start) }
        val image = async { getResponse("image", start) }
        val sss = async { getResponse("sss", start) }
        val ss2 = async { getResponse("ss2", start) }
//        for (i in 3..900) {
//            async { site.tiangao.async.kt.getRes("ss$i", start) }
//        }
        println("${dal.await()} ${redis.await()} ${image.await()} ${sss.await()} ${ss2.await()}")
        println("cost : ${System.currentTimeMillis() - start}ms")
    }
//    System.exit(0)
//    Thread.sleep(20000)
}

suspend fun getResponse(s: String, start: Long): String {
    println("$s start ${System.currentTimeMillis() - start}")
    val url = "http://localhost:8086/$s"
    val future = httpClient.prepareGet(url).execute()
    while (!future.isDone) {
        delay(1)
    }
    println("$s end ${System.currentTimeMillis() - start}")
    return future.get().responseBody
}

